<template>
  <view class="container">


    <!-- 表单 -->
    <view class="form-container">
      <!-- 头像上传 -->
      <view class="avatar-section">
        <view class="avatar-upload" @click="chooseAvatar">
          <image 
            v-if="displayAvatar" 
            :src="displayAvatar" 
            class="avatar-image" 
            mode="aspectFill"
            @error="onAvatarError"
            @load="onAvatarLoad"
          ></image>
          <view v-else class="avatar-placeholder">
            <text class="avatar-icon">👤</text>
            <text class="avatar-text">点击上传头像</text>
          </view>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="form-section">
        <view class="form-item">
          <text class="label">昵称 <text class="required">*</text></text>
          <input 
            v-model="formData.nickName" 
            placeholder="请输入昵称" 
            class="input"
            maxlength="20"
          />
        </view>

        <view class="form-item">
          <text class="label">性别</text>
          <picker 
            :value="genderIndex" 
            :range="sexOptions" 
            range-key="label"
            @change="onGenderChange"
            class="picker"
          >
            <view class="picker-text">
              {{ sexLabel }}
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">手机号</text>
          <input 
            v-model="formData.phonenumber" 
            placeholder="请输入手机号" 
            class="input"
            maxlength="11"
            type="number"
          />
        </view>

        <view class="form-item">
          <text class="label">邮箱</text>
          <input 
            v-model="formData.email" 
            placeholder="请输入邮箱" 
            class="input"
            type="email"
          />
        </view>

       <!-- <view class="form-item textarea-item">
          <text class="label">备注</text>
          <textarea 
            v-model="formData.remark" 
            placeholder="请输入备注信息" 
            class="textarea"
            maxlength="200"
          />
        </view>-->
      </view>
    </view>

    <!-- 底部保存按钮 -->
    <view class="bottom-bar">
      <button class="save-btn" @click="saveProfile" :disabled="loading">保存</button>
    </view>
  </view>
</template>

<script>
import { getUserId, checkAndRedirectToLogin } from '@/utils/auth.js'
import { getToken } from '@/utils/auth.js'
import { updateUserProfile, uploadUserAvatar } from '@/api/user.js'
import { API_BASE } from '@/config/config.js'

export default {
  data() {
    return {
      formData: {
        nickName: '',
        sex: '',
        phonenumber: '',
        email: '',
        avatar: '',
        remark: ''
      },
      sexOptions: [
        { label: '男', value: '0' },
        { label: '女', value: '1' },
        { label: '未知', value: '2' }
      ],
      genderIndex: -1,
      loading: false,
      apiBase: API_BASE,
      originalAvatar: '' // 记录原始头像，用于比较
    }
  },
  onLoad() {

    const token = getToken()

    if (!token) {
      uni.showToast({ title: '未检测到登录信息，即将跳转到登录页面', icon: 'none' })
      setTimeout(() => {
        uni.navigateTo({ url: '/pages/login?from=profile' })
      }, 2000)
    } else {
      console.log('Token exists, skipping forced validation to avoid issues')
      // 注释掉 token 验证，避免重复验证导致的问题
      /*
      uni.request({
        url: `${API_BASE}/system/user/profile`,
        method: 'GET',
        header: { 'Authorization': `Bearer ${token}` },
        success: (res) => {
          if (res.statusCode !== 200) {
            uni.showToast({ title: '登录已过期，即将跳转到登录页面', icon: 'none' })
            setTimeout(() => {
              uni.navigateTo({ url: '/pages/login?from=profile' })
            }, 2000)
          } else {

          }
        },
        fail: (err) => {

          uni.showToast({ title: '无法验证登录状态，即将跳转到登录页面', icon: 'none' })
          setTimeout(() => {
            uni.navigateTo({ url: '/pages/login?from=profile' })
          }, 2000)
        }
      })
      */
    }
    this.loadUserInfo()
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    chooseAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const localPath = res.tempFilePaths[0]
          // 先本地预览
          this.formData.avatar = localPath
          // 上传到服务器
          this.uploadAvatar(localPath)
        }
      })
    },
    
    async uploadAvatar(filePath) {
      const token = getToken()
      if (!token) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        uni.navigateTo({ url: '/pages/login?from=profile' })
        return
      }
      uni.showLoading({ title: '上传中...' })
      try {

        // 注释掉 token 验证，避免重复验证导致的问题
        /*
        // 验证 token 是否有效
        const tokenCheck = await new Promise((resolve) => {
          uni.request({
            url: `${API_BASE}/system/user/profile`,
            method: 'GET',
            header: { 'Authorization': `Bearer ${token}` },
            success: (res) => {
              resolve(res.statusCode === 200)
            },
            fail: () => {
              resolve(false)
            }
          })
        })
        if (!tokenCheck) {
          uni.showToast({ title: '认证失败，可能需要重新登录', icon: 'none' })
          // 不强制清除缓存和跳转，让用户决定是否重新登录
          uni.hideLoading()
          return
        }
        */
        const data = await uploadUserAvatar(filePath, token)

        if (data && data.code === 200) {
          const imgUrl = data.imgUrl || (data.data && (data.data.imgUrl || data.data.url))
          if (imgUrl) {
            // 处理头像URL - 后端返回的是相对路径，需要拼接完整URL
            let finalAvatarUrl = imgUrl
            
            // 如果后端返回的是 /profile/avatar/... 格式，直接使用
            if (imgUrl.startsWith('/profile/')) {
              finalAvatarUrl = imgUrl
            } else if (imgUrl.startsWith('/')) {
              // 其他相对路径，直接使用
              finalAvatarUrl = imgUrl
            } else if (!imgUrl.startsWith('http')) {
              // 文件名，拼接完整URL
              finalAvatarUrl = `/profile/avatar/${imgUrl}`
            }
            

            
            // 更新表单数据
            this.formData.avatar = finalAvatarUrl
            
            // 同步到本地 userInfo
            const cached = uni.getStorageSync('userInfo') || {}
            const updatedUserInfo = { ...cached, avatar: finalAvatarUrl }
            uni.setStorageSync('userInfo', updatedUserInfo)
            
            // 强制触发页面重新渲染
            this.$forceUpdate()
            
            // 延迟一下再显示成功提示，确保页面更新
            setTimeout(() => {
              uni.showToast({ title: '头像已更新', icon: 'success' })
            }, 100)
            
          } else {
            uni.showToast({ title: '上传成功但未返回地址', icon: 'none' })
          }
        } else {

          uni.showToast({ title: (data && data.msg) || '上传失败', icon: 'none' })
        }
      } catch (error) {

        // 检查是否是网络相关错误
        if (error.errMsg && error.errMsg.includes('fail')) {
          uni.showToast({ title: '网络错误，请检查网络连接', icon: 'none' })
        } else {
          uni.showToast({ title: '上传失败: ' + (error.message || error.errMsg || '未知错误'), icon: 'none' })
        }
      } finally {
        uni.hideLoading()
      }
    },
    
    onGenderChange(e) {
      const index = Number(e.detail.value)
      this.genderIndex = index
      const option = this.sexOptions[index]
      this.formData.sex = option ? option.value : ''
    },
    
    onAvatarLoad(e) {
      // 只有在实际加载新头像时才显示成功提示，避免页面加载时误触发
      if (this.formData.avatar && this.formData.avatar !== this.originalAvatar) {
        uni.showToast({ title: '头像加载成功', icon: 'success' })
      }
    },
    
    onAvatarError(e) {

      // 只有在不是默认头像的情况下才显示错误提示
      if (this.displayAvatar && !this.displayAvatar.includes(''
      }
      
      // 如果是完整的URL，直接返回
      if (/^https?:\/\//i.test(raw)) {
          return raw + '?t=' + Date.now()
      }
      
      // 如果是相对路径，添加完整URL
      if (raw.startsWith('/')) {
        // 强制修复到正确的路径
        let fixedPath = raw
        if (fixedPath.includes('/system/user/profile/avatar/')) {
          fixedPath = fixedPath.replace('/system/user/profile/avatar/', '/profile/avatar/')

        }
        const fullUrl = `${API_BASE}${fixedPath}`
        return fullUrl + '?t=' + Date.now()
      }
      
      // 如果是文件名，添加完整路径
      const fullUrl = `${API_BASE}/${raw}`
      return fullUrl + '?t=' + Date.now()
    },
    sexLabel() {
      const code = String(this.formData.sex || '')
      const found = this.sexOptions.find(o => o.value === code)
      return found ? found.label : '请选择性别'
    }
  }
}
</script>

<style scoped>
.container {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 140rpx; /* 预留底部按钮空间 */
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.back-btn, .save-btn {
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 30rpx;
  font-size: 28rpx;
}

/* 仅保存按钮占满底部栏宽度 */
.save-btn {
  width: 100%;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

.form-container {
  padding: 20rpx;
}

/* 底部固定操作栏 */
.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 20rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.avatar-section {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.avatar-title {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.avatar-upload {
  width: 150rpx;
  height: 150rpx;
  border: 2px dashed #ddd;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
}

.avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-icon {
  font-size: 50rpx;
  margin-bottom: 10rpx;
}

.avatar-text {
  font-size: 20rpx;
  color: #999;
}

.form-section {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
}

.label {
  display: block;
  width: 180rpx;
  flex-shrink: 0;
  font-size: 28rpx;
  color: #333;
  margin-right: 20rpx;
  font-weight: bold;
}

.required {
  color: #ff4d4f;
}

.input, .picker, .textarea {
  flex: 1;
  min-height: 36rpx;
  padding: 10rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
}

.picker-text {
  color: #333;
}

.textarea {
  height: 80rpx;
  resize: none;
}

.textarea-item {
  align-items: flex-start;
}

.input:focus, .textarea:focus {
  border-color: #007AFF;
}
</style>
